#!/bin/bash

# iptables -t nat -A OUTPUT -d 192.168.0.22 -p tcp --dport 6443 -j DNAT --to-destination 172.20.150.48:6443
# 授权数据 资源文件路径 执行的操作

# JIANMU_COMMAND
# JIANMU_RESOURCE_FILE_PATH
# JIANMU_CERTIFICATE_AUTHORITY_DATA
# JIANMU_SERVER
# JIANMU_CLIENT_CERTIFICATE_DATA
# JIANMU_CLIENT_KEY_DATA
set -e
JIANMU_REGISTRY=ygcx-image-registry.tencentcloudcr.com
image_name="${JIANMU_REGISTRY}/ai/${JIANMU_JOB_NAME}:${JIANMU_NAMESPACE}-${JIANMU_BUILD_NUMBER}"

ls -l

generate_certificate() {
  mkdir -p "/root/.kube"
  python ./build_configuration.py
  echo "build kubeconfig complete"
}


check_resources() {
  # k8s检查服务
  # 判断环境变量 JIANMU_WAIT_TIME 是否已设置并且是数字
  if [[ -n $JIANMU_WAIT_TIME && $JIANMU_WAIT_TIME =~ ^[0-9]+$ ]]; then
    echo "检查服务运行状态前,等待 $JIANMU_WAIT_TIME 秒"
    sleep $JIANMU_WAIT_TIME
  fi
  pods_info=$(kubectl --kubeconfig=/root/.kube/config get pods -n ai-${JIANMU_NAMESPACE} | grep ${JIANMU_JOB_NAME})
  # 分析并输出结果
  if [ -z "$pods_info" ]; then
    notify_text="未找到与[Jianmu_NAMESPACE: ai-$JIANMU_NAMESPACE, Jianmu_JOB_NAME: $JIANMU_JOB_NAME]匹配的Pods"
    echo "$notify_text"
    python ./notify.py "$notify_text"
    exit 1
  fi
  echo "找到以下Pods:"
  echo "$pods_info"
    
  # 进一步分析，确定所有pods的状态
  echo "检查Pods的状态:"
  notify_text=""
  # 使用while read命令逐行读取pods_info的内容
  while read -r pod_line; do
    pod_name=$(echo "$pod_line" | awk '{print $1}')
    current_status=$(echo "$pod_line" | awk '{print $3}')

    if [ "$current_status" != "Running" ]; then
      notify_text+="Pod名称:$pod_name,当前状态:$current_status\n"
    fi
  done <<< "$pods_info"

  # 如果有异常状态，发送通知
  if [[ -n "$notify_text" ]]; then
    echo -e "$notify_text"
    python ./notify.py "$notify_text"
    exit 1
  fi
 
  #提取Pod名称
  echo "expect image: ${image_name}"
  pod_names=($(echo "$pods_info" | awk '{print $1}'))
  for pod_name in "${pod_names[@]}"; do
      # 查看每个pod的镜像
      pod_image=$(kubectl --kubeconfig=/root/.kube/config get pods $pod_name -n ai-${JIANMU_NAMESPACE} -o jsonpath='{.spec.containers[*].image}')
      echo "pod image:$pod_image"
      if [ "$pod_image" != "$image_name" ]; then
        echo "pod image not match expected image"
        if [ -z "$notify_text" ]; then
          notify_text+="预期image: $image_name\n"
        fi
        notify_text+="Pod: $pod_name,image: $pod_image,不符合预期\n"
      fi
  done
  if [ -n "$notify_text" ]; then
    python ./notify.py "$notify_text"
    exit 1
  fi
  echo "kube check complete"
}

generate_certificate
check_resources
